class Music {

    constructor() {
        this.ctx = new (window.AudioContext || window.webkitAudioContext())();
        this.source = this.ctx.createBufferSource(); // 创建音频源头姐点
    }

    // 播放
    async playAudio(musicSrc) {
        const audioBuffer = await this.loadAudio(musicSrc);
        this.playSound(audioBuffer);
        let _this = this
        setTimeout(() => _this.stopAudio(), 800)
    }


    // 暂停 
    async resumeAudio() {
        if (this.ctx.state === "running") {
            this.ctx.suspend();
        } else if (this.ctx.state === "suspended") {
            this.ctx.resume();
        }
    }

    // 停止
    async stopAudio() {
        this.source.stop();
    }

    async loadAudio(musicSrc) {
        const audioUrl = musicSrc;
        const res = await fetch(audioUrl);
        const arrayBuffer = await res.arrayBuffer(); // byte array字节数组
        const audioBuffer = await this.ctx.decodeAudioData(arrayBuffer, function (decodeData) {
            return decodeData;
        });
        return audioBuffer;
    }

    async playSound(audioBuffer) {
        this.source.buffer = audioBuffer; // 设置数据
        this.source.loop = true; //设置，循环播放
        this.source.connect(this.ctx.destination); // 头尾相连
        // 可以对音频做任何控制
        this.source.start(0); //立即播放
    }

}


export default Music;
